<template>
    <el-upload class="avatar-uploader" :action="action" :show-file-list="showFileList" :on-success="onSuccess" :http-request="onUpload" :before-upload="onBeforeUpload">
        <img v-if="url" :src="url" class="avatar" :style="{ width: width + 'px', height: width + 'px' }" />
        <el-icon v-else class="avatar-uploader-icon" :style="{ padding: width / 2 + 'px' }"><Plus /></el-icon>
    </el-upload>
</template>

<script setup lang="ts">
import { inject } from "vue";

//获取自定义全局方法
const { emitter, http } = inject<any>("method");

//父传子
interface Props {
    action?: string;
    showFileList?: boolean;
    uploadUrl?: string;
    width?: number;
    maxSize?: number | string | null;
}
const props = withDefaults(defineProps<Props>(), {
    action: "",
    showFileList: false,
    uploadUrl: "",
    width: 100,
    maxSize: null,
});

const url = defineModel<string>({ type: String, default: null });

//允许上传图片的类型
const imageType: Array<string> = ["image/png", "image/jpeg", "image/gif", "image/jpg"];

//上传之前
const onBeforeUpload = (file: any) => {
    if (imageType.findIndex((type: string) => type == file.type) < 0) {
        emitter.emit("msg-error", "请上传合法的图片！");
        return false;
    }
    if (props.maxSize && file.size > toByte(props.maxSize)) {
        emitter.emit("msg-error", "图片文件过大，限制" + props.maxSize + "！");
        return false;
    }
    return true;
};

//转换字节
const toByte = (size: number | string) => {
    if (typeof size == "number") return size;
    const s = size.toLowerCase();
    if (s.indexOf("kb") > -1) {
        return parseInt(s.replace("kb", "")) * 1024;
    } else if (s.indexOf("mb") > -1) {
        return parseInt(s.replace("mb", "")) * 1024 * 1024;
    } else if (s.indexOf("gb") > -1) {
        return parseInt(s.replace("gb", "")) * 1024 * 1024 * 1024;
    } else {
        return parseInt(s);
    }
};

//执行上传
const onUpload = async (file: any) => {
    const data = await http.upload(props.uploadUrl, file.file);
    if (data?.success) {
        url.value = data?.data?.url;
    }
};

//上传成功
const onSuccess = () => {
    console.info("onSuccess");
};
</script>

<style scoped lang="less">
@width: 5px;
@bgcolor: rgba(59, 0, 251, 1);

.avatar {
    border-radius: @width;
}

.avatar:hover {
    border-radius: @width;
    border: 1px solid @bgcolor;
}

.avatar-uploader-icon {
    border: 1px solid rgba(200, 200, 200, 0.7);
    border-radius: @width;
}

.avatar-uploader-icon:hover {
    border: 1px solid @bgcolor;
    border-radius: @width;
}
</style>
